package thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by User on 2017/12/25.
 */
public class ThreadInterrupt {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        WorkThread wThread = new WorkThread(lock);
        wThread.start();
        System.out.println("开始调用lock.lock()");
        lock.lock();
        System.out.println("结束调用lock.lock()");
        Thread.sleep(5000);
        System.out.println("开始调用wThread.interrupt()");
        wThread.interrupt();
        System.out.println("结束调用wThread.interrupt()");
        Thread.sleep(5000);
        System.out.println("开始调用lock.unlock()");
        lock.unlock();
        System.out.println("结束调用lock.unlock()");
    }

}

class WorkThread extends Thread {

    Lock lock;

    public WorkThread(Lock lock) {
        this.lock = lock;
    }

    public void run() {
        System.out.println("工作线程sleep");
        for (int i = 0; i < Byte.MAX_VALUE;) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
            try {
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
            try {
                sleep(10 * 1000);
                System.out.println("工作线程运行"+(++i));
            } catch (InterruptedException e) {
                System.out.println("工作线程InterruptedException");
                break;
            }
        }
        System.out.println("工作线程运行完毕");
    }

}